<script setup lang="ts">
import { computed, reactive, ref, toRaw } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { user_info_api } from "@/package/guider/api/guide_certification";
import {
  types_api,
  info_api,
  add_api,
} from "@/package/guider/api/new_guide_certification";
import { get_identity_type_list_api } from "@/package/guider/api/tour_info";
import { upload_up } from "@/api/upload";
import { AppData } from "@/utils/app";
import { chooseMedia } from "@/utils/meida";
import { Storage } from "@/utils/database";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import EditMenuTitle from "./components/edit-menu-title.vue";
import EditIdentityPicker from "./components/edit-identity-picker.vue";
import FormPicker from "@/components/form/picker.vue";
import EditCertificateItem from "./components/edit-certificate-item.vue";
import EditCertificateForm from "./components/edit-certificate-form.vue";
import FormCheckbox from "@/components/form/checkbox.vue";
import EditImgList from "./components/edit-img-list.vue";
import FormButton from "@/components/form/button.vue";
import PopupCenter from "@/components/popup/center.vue";

const formKey = "guider-apply-edit-form";

onLoad((options) => {
  const type = Number(options?.type || 1);
  uni.setNavigationBarTitle({
    title:
      type === 1
        ? "持证导游身份认证"
        : type === 2
        ? "非·持证导游认证"
        : type === 3
        ? "海外导游认证"
        : "考生认证",
  });
  editForm.type = type;
  user_info_api(false).then((resp) => {
    if (editForm.avatar_url) return;
    editForm.avatar_url = resp.avatar_url;
  });
  info_api({ type }).then((resp) => {
    if (!resp) return;
    editForm.avatar_url = resp.avatar_url;
    editForm.name = resp.name;
    editForm.card_type = resp.card_type;
    editForm.card_no = resp.card_no;
    editForm.gender = resp.gender;
    editForm.phone = resp.phone;
    editForm.city_id = resp.city_id;
    infoData.city_name = resp.city_name;
    editForm.identity_type = resp.identity_type || [];
    editForm.guider_date = resp.guider_date;
    editForm.guider_no = resp.guider_no;
    editForm.guider_level = resp.guider_level;
    editForm.guider_pic = resp.guider_pic;
    editForm.language_arr = resp.language_arr;
    editForm.tutor_no = resp.tutor_no;
    editForm.tutor_date = resp.tutor_date;
    editForm.tutor_pics = resp.tutor_pics || [];
    editForm.leader_no = resp.leader_no;
    editForm.leader_date = resp.leader_date;
    editForm.leader_pics = resp.leader_pics || [];
    editForm.prove_img = resp.prove_img || [];
    editForm.honor_img = resp.honor_img || [];
    editForm.card_valid_date = resp.card_valid_date;
    editForm.wechat = resp.wechat;
    editForm.card_pics = resp.card_pics || [];
    editForm.remark = resp.remark;
  });

  if (type === 1) {
    types_api().then((resp) => {
      levelList.value = resp.guider_rank;
      languageList.value = resp.language;
      exampleImg.value = resp.example_card_pic;
    });
  } else if (type === 3) {
    get_identity_type_list_api().then((resp) => {
      certificateList.value = resp.identity_type;
    });
  }

  // 上次缓存
  const form = Storage.getSync(formKey);
  if (form) {
    const data = form[type];
    if (data) {
      const _editForm = data.editForm;
      const _infoData = data.infoData;
      editForm.avatar_url = _editForm.avatar_url;
      editForm.name = _editForm.name;
      editForm.card_type = _editForm.card_type;
      editForm.card_no = _editForm.card_no;
      editForm.gender = _editForm.gender;
      editForm.phone = _editForm.phone;
      editForm.city_id = _editForm.city_id;
      infoData.city_name = _infoData.city_name;
      editForm.identity_type = _editForm.identity_type || [];
      editForm.guider_date = _editForm.guider_date;
      editForm.guider_no = _editForm.guider_no;
      editForm.guider_level = _editForm.guider_level;
      editForm.guider_pic = _editForm.guider_pic;
      editForm.language_arr = _editForm.language_arr;
      editForm.tutor_no = _editForm.tutor_no;
      editForm.tutor_date = _editForm.tutor_date;
      editForm.tutor_pics = _editForm.tutor_pics || [];
      editForm.leader_no = _editForm.leader_no;
      editForm.leader_date = _editForm.leader_date;
      editForm.leader_pics = _editForm.leader_pics || [];
      editForm.prove_img = _editForm.prove_img || [];
      editForm.honor_img = _editForm.honor_img || [];
      editForm.card_valid_date = _editForm.card_valid_date;
      editForm.wechat = _editForm.wechat;
      editForm.card_pics = _editForm.card_pics || [];
      editForm.remark = _editForm.remark;
    }
  }

  uni.enableAlertBeforeUnload({ message: "您确定要放弃身份认证?" });
});
onUnload(() => {
  if (tempData.isSubmit) return;

  let form = Storage.getSync(formKey);
  if (form) {
    form[editForm.type] = {
      editForm: toRaw(editForm),
      infoData: toRaw(infoData),
    };
  } else {
    form = {
      [editForm.type]: { editForm: toRaw(editForm), infoData: toRaw(infoData) },
    };
  }
  Storage.setSync(formKey, form);
});

const editForm = reactive({
  type: 1,
  avatar_url: "",
  name: "",
  card_type: 1,
  card_no: "",
  gender: 1,
  phone: "",
  city_id: "",
  identity_type: [] as number[],
  guider_date: "",
  guider_no: "",
  guider_level: 1,
  guider_pic: "",
  language_arr: "",
  tutor_no: "",
  tutor_date: "",
  tutor_pics: [] as string[],
  leader_no: "",
  leader_date: "",
  leader_pics: [] as string[],
  prove_img: [] as string[],
  honor_img: [] as string[],
  card_valid_date: "",
  wechat: "",
  card_pics: [] as string[],
  remark: "",
});
const infoData = reactive({ city_name: "" });

const guiderClick = (id: number) => {
  const index = editForm.identity_type.indexOf(id);
  index === -1
    ? editForm.identity_type.push(id)
    : editForm.identity_type.splice(index, 1);
};
const levelList = ref<any[]>([]);
const languageList = ref<any[]>([]);
const exampleImg = ref("");

const certificateIndex = computed({
  get() {
    return certificateList.value.findIndex((i) => i.id === editForm.card_type);
  },
  set(index) {
    editForm.card_type = certificateList.value[index].id;
  },
});
const certificateList = ref<any[]>([]);

const avatarClick = () => {
  chooseMedia({ count: 1, mediaType: ["image"] }, (fileList) => {
    Toast.showLoading();
    upload_up(fileList[0].tempFilePath, { type: 2 })
      .then((resp) => {
        editForm.avatar_url = resp[0].url;
        Toast.hideLoading();
      })
      .catch(() => Toast.hideLoading());
  });
};
const areaClick = () => {
  Router.navigateTo("/package/other/pages/destination/index", (resp) => {
    resp.eventChannel.emit("ev-destination-data", {
      title: "常驻地选择",
    });
    resp.eventChannel.once("ev-destination-data", (resp) => {
      if (resp) {
        editForm.city_id = resp.id;
        infoData.city_name = resp.name;
        Router.navigateBack();
      }
    });
  });
};

const submitClick = () => {
  Toast.showLoading();
  add_api(toRaw(editForm))
    .then((resp) => {
      Toast.hideLoading();
      resultVisible.value = true;
      tempData.isSubmit = true;
      uni.disableAlertBeforeUnload();
      uni.$emit("ev-apply");
    })
    .catch(() => Toast.hideLoading());
};

const resultVisible = ref(false);
const resultClcik = (type: number) => {
  if (type === 1) {
    AppData.initConfig((config) => {
      Router.redirectTo(config.guider_certification);
    });
  } else {
    const pages = getCurrentPages();
    const page = pages[pages.length - 2];
    page.route?.includes("package/guider/pages/apply/edit")
      ? Router.navigateBack(2)
      : Router.navigateBack();
  }
};

const tempData = { isSubmit: false };
</script>

<template>
  <view class="edit-tip">
    <image
      class="edit-tip-icon"
      src="@/package/guider/static/apply-edit-certificate.png"
    />
    信息仅用于身份认证，平台保障您的信息安全
  </view>

  <EditIdentityPicker
    v-if="editForm.type === 2"
    v-model="editForm.identity_type"
  />

  <view class="edit-info">
    <view class="edit-info-title">
      <EditMenuTitle title="个人资料" required />
    </view>
    <view class="edit-info-item">
      <view class="edit-info-label">头像</view>
      <view class="edit-info-content" @click="avatarClick">
        <image
          class="edit-info-avatar"
          :src="editForm.avatar_url"
          mode="aspectFill"
        />
        <image
          class="edit-info-arrow"
          src="@/package/guider/static/apply-edit-arrow.png"
        />
      </view>
    </view>
    <view class="edit-info-line"></view>
    <view class="edit-info-item">
      <view class="edit-info-label">姓名</view>
      <view class="edit-info-content">
        <input
          class="edit-info-input"
          v-model="editForm.name"
          placeholder="请填写您的姓名"
        />
      </view>
    </view>
    <view class="edit-info-line"></view>
    <template v-if="editForm.type === 1 || editForm.type === 2">
      <view class="edit-info-item">
        <view class="edit-info-label">身份证号</view>
        <view class="edit-info-content">
          <input
            class="edit-info-input"
            v-model="editForm.card_no"
            placeholder="请填写您的身份证号码"
          />
        </view>
      </view>
      <view class="edit-info-line"></view>
    </template>
    <template v-else-if="editForm.type === 3">
      <view class="edit-info-item">
        <view style="flex-shrink: 0">
          <FormPicker
            v-model="certificateIndex"
            :range="certificateList"
            rangeKey="name"
          >
            <view style="display: flex; align-items: center">
              <view class="edit-info-label">
                {{
                  certificateIndex === -1
                    ? "证件类型"
                    : certificateList[certificateIndex].name
                }}
              </view>
              <image
                class="edit-info-arrow2"
                src="@/package/guider/static/apply-edit-arrow2.png"
              />
            </view>
          </FormPicker>
        </view>
        <view class="edit-info-content">
          <input
            class="edit-info-input"
            v-model="editForm.card_no"
            placeholder="请填写对应的证件号码"
          />
        </view>
      </view>
      <view class="edit-info-line"></view>
      <view class="edit-info-item">
        <view class="edit-info-label">证件有效期</view>
        <view style="flex-grow: 1; min-width: 0">
          <FormPicker v-model="editForm.card_valid_date" mode="date">
            <view class="edit-info-content">
              <view class="edit-info-value">
                {{ editForm.card_valid_date || "请选择日期" }}
              </view>
              <image
                class="edit-info-arrow"
                src="@/package/guider/static/apply-edit-arrow.png"
              />
            </view>
          </FormPicker>
        </view>
      </view>
      <view class="edit-info-line"></view>
    </template>
    <view class="edit-info-item">
      <view class="edit-info-label">性别</view>
      <view class="edit-info-content">
        <view class="edit-info-checkbox" @click="editForm.gender = 1">
          <FormCheckbox :modelValue="editForm.gender === 1" />&nbsp;男
        </view>
        <view class="edit-info-checkbox" @click="editForm.gender = 2">
          <FormCheckbox :modelValue="editForm.gender === 2" />&nbsp;女
        </view>
      </view>
    </view>
    <view class="edit-info-line"></view>
    <view class="edit-info-item">
      <view class="edit-info-label">电话</view>
      <view class="edit-info-content">
        <input
          class="edit-info-input"
          v-model="editForm.phone"
          type="number"
          placeholder="请填写微信关联的手机号"
        />
      </view>
    </view>
    <view class="edit-info-line"></view>
    <template v-if="editForm.type === 3">
      <view class="edit-info-item">
        <view class="edit-info-label">社交媒体账号或邮箱</view>
        <view class="edit-info-content">
          <textarea
            class="edit-info-textarea"
            v-model="editForm.wechat"
            auto-height
            placeholder="请填写账号或邮箱"
          />
          <!-- <input
            class="edit-info-input"
            v-model="editForm.wechat"
            placeholder="请填写账号或邮箱"
          /> -->
        </view>
      </view>
      <view class="edit-info-line"></view>
    </template>
    <view class="edit-info-item">
      <view class="edit-info-label">常驻地</view>
      <view class="edit-info-content">
        <view class="edit-info-value" @click="areaClick">
          {{ editForm.city_id ? infoData.city_name : "请选择国家/地区" }}
        </view>
        <image
          class="edit-info-arrow"
          src="@/package/guider/static/apply-edit-arrow.png"
        />
      </view>
    </view>
    <view class="edit-info-line"></view>
  </view>

  <view class="edit-certificate" v-if="editForm.type === 1">
    <view class="edit-certificate-title">
      <EditMenuTitle
        title="请选择需要认证的身份类别"
        required
        desc="(可复选)"
      />
    </view>
    <view class="edit-certificate-wrapper">
      <view @click="guiderClick(9)">
        <EditCertificateItem
          text="中文导游"
          :isActive="editForm.identity_type.includes(9)"
        />
      </view>
      <EditCertificateForm
        v-if="editForm.identity_type.includes(9)"
        :formId="9"
        :modelValue="editForm"
        :levelData="levelList"
        :languageData="languageList"
        :exampleImg="exampleImg"
      />
    </view>
    <view class="edit-certificate-wrapper">
      <view @click="guiderClick(10)">
        <EditCertificateItem
          text="外文导游"
          :isActive="editForm.identity_type.includes(10)"
        />
      </view>
      <EditCertificateForm
        v-if="editForm.identity_type.includes(10)"
        :formId="10"
        :modelValue="editForm"
        :levelData="levelList"
        :languageData="languageList"
        :exampleImg="exampleImg"
      />
    </view>
    <view class="edit-certificate-wrapper">
      <view @click="guiderClick(8)">
        <EditCertificateItem
          text="研学导师"
          :isActive="editForm.identity_type.includes(8)"
        />
      </view>
      <EditCertificateForm
        v-if="editForm.identity_type.includes(8)"
        :formId="8"
        :modelValue="editForm"
        :levelData="levelList"
        :languageData="languageList"
      />
    </view>
    <view class="edit-certificate-wrapper">
      <view @click="guiderClick(11)">
        <EditCertificateItem
          text="出境领队"
          :isActive="editForm.identity_type.includes(11)"
        />
      </view>
      <EditCertificateForm
        v-if="editForm.identity_type.includes(11)"
        :formId="11"
        :modelValue="editForm"
        :levelData="levelList"
        :languageData="languageList"
      />
    </view>
  </view>
  <template v-else-if="editForm.type === 2">
    <EditImgList
      :listData="editForm.prove_img"
      title="相关证明"
      required
      desc="从事过讲解服务的证明、用户评价。以及相关自媒体账号或文博相关专业的学历证明等"
    />
    <EditImgList
      :listData="editForm.honor_img"
      title="证书"
      desc="高校、文旅企业或行业组织颁发的相关证书"
    />
  </template>
  <EditImgList
    v-else-if="editForm.type === 4"
    :listData="editForm.prove_img"
    title="相关证明资料"
    required
    desc="请上传学生证、报考证明"
  />
  <EditImgList
    v-else-if="editForm.type === 3"
    :listData="editForm.card_pics"
    title="上传身份证件"
    required
  />

  <view class="edit-remark">
    <view class="edit-remark-title">
      <EditMenuTitle title="补充说明" />
    </view>
    <view class="edit-remark-content">
      <textarea
        class="edit-remark-input"
        v-model="editForm.remark"
        auto-height
        placeholder="可在此补充说明您从事相关行业的其他证明，如自媒体账号等，有助于审核通过"
      />
    </view>
  </view>

  <view class="edit-btn">
    <view @click="submitClick">
      <FormButton>提交审核</FormButton>
    </view>
  </view>

  <PopupCenter :modelValue="resultVisible" :showClose="false">
    <view class="edit-result">
      <view class="edit-result-title">{{ editForm.name }}您好！欢迎回家</view>
      <view class="edit-result-content">
        欢迎加入全球导游/向导一站式服务平台，成为百万导游人大家庭中的一员，让我们携手并肩，同心同行！
        如需启动你的个人自由执业，请您进一步完善个人信息，以便我们更深入地了解您的专长及匹配合适用户。只需轻松完成接单资质的专业认证，即可解锁接单权限，开启全新的服务篇章。
      </view>
      <view class="edit-result-btn" @click="resultClcik(1)">
        前往带团宝认证接单资质
      </view>
      <view class="edit-result-btn2" @click="resultClcik(2)">以后再说</view>
    </view>
  </PopupCenter>
</template>

<style lang="scss">
page {
  padding-top: 40rpx;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;
}

.edit-tip {
  display: flex;
  align-items: center;
  height: 64rpx;
  padding-left: 20rpx;
  margin: 0 30rpx 34rpx;
  font-size: 28rpx;
  color: #ffa300;
  line-height: 40rpx;
  border-radius: 10rpx;
  background-color: rgba(255, 163, 0, 0.05);

  .edit-tip-icon {
    width: 36rpx;
    height: 36rpx;
    margin-right: 10rpx;
  }
}

.edit-info {
  margin-bottom: 34rpx;

  .edit-info-title {
    padding-left: 30rpx;
  }

  .edit-info-item {
    display: flex;
    align-items: center;
    min-height: 72rpx;
    padding: 14rpx 60rpx 14rpx 30rpx;
  }

  .edit-info-label {
    flex-shrink: 0;
    font-size: 28rpx;
    color: #666666;
    line-height: 40rpx;
  }

  .edit-info-content {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-grow: 1;
    min-width: 0;
    margin-left: 20rpx;
  }

  .edit-info-avatar {
    width: 76rpx;
    height: 76rpx;
    border-radius: 50%;
  }

  .edit-info-arrow {
    flex-shrink: 0;
    width: 24rpx;
    height: 24rpx;
    margin-left: 20rpx;
  }

  .edit-info-line {
    margin: 0 30rpx;
    border-bottom: 2rpx solid #dddddd;
  }

  .edit-info-input,
  .edit-info-checkbox,
  .edit-info-value,
  .edit-info-textarea {
    font-size: 30rpx;
    color: #333333;
    line-height: 42rpx;
    text-align: right;
  }

  .edit-info-input {
    flex-grow: 1;
    min-width: 0;
  }

  .edit-info-arrow2 {
    width: 20rpx;
    height: 20rpx;
    margin-left: 10rpx;
  }

  .edit-info-checkbox {
    display: flex;
    align-items: center;
    margin-left: 60rpx;
  }
}

.edit-certificate {
  padding-bottom: 14rpx;

  .edit-certificate-title {
    padding-left: 30rpx;
    margin-bottom: 14rpx;
  }

  .edit-certificate-wrapper {
    margin-bottom: 20rpx;
  }
}

.edit-remark {
  .edit-remark-title {
    padding-left: 30rpx;
  }

  .edit-remark-content {
    padding: 40rpx 30rpx;
  }

  .edit-remark-input {
    display: block;
    width: 100%;
    min-height: 264rpx;
    padding: 30rpx;
    font-size: 28rpx;
    color: #333333;
    line-height: 40rpx;
    border-radius: 20rpx;
    background-color: #f9f9f9;
    box-sizing: border-box;
  }
}

.edit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 106rpx;
  padding: 14rpx 60rpx env(safe-area-inset-bottom);
  background-color: #ffffff;
}

.edit-result {
  position: relative;
  width: 74vw;
  padding: 80rpx 40rpx 30rpx;
  box-sizing: border-box;

  .edit-result-title {
    margin-bottom: 40rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 44rpx;
    text-align: center;
    font-weight: bold;
  }

  .edit-result-content {
    margin-bottom: 40rpx;
    font-size: 28rpx;
    color: #666666;
    line-height: 42rpx;
    text-align: center;
  }

  .edit-result-btn,
  .edit-result-btn2 {
    width: 380rpx;
    margin: 0 auto 30rpx;
    font-size: 28rpx;
    color: #ffffff;
    line-height: 76rpx;
    text-align: center;
    font-weight: bold;
    border-radius: 44rpx;
    background-color: #ff7900;
  }

  .edit-result-btn2 {
    width: 376rpx;
    color: #999999;
    line-height: 72rpx;
    border: 2rpx solid #999999;
    background-color: transparent;
  }
}
</style>